package com.vectorimage.compress;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.vectorimage.entity.Face;
import com.vectorimage.entity.ReadFaces;
import com.vectorimage.util.DefaultFacesReader;
import com.vectorimage.util.Tool;

/**
 * 获取图片信息
 * @author smilence
 *
 */
public class ScaleImage extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ScaleImage() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String oldFile = request.getSession().getServletContext().getRealPath(request.getParameter("img"));
		String outputDir = oldFile.substring(0, oldFile.lastIndexOf(File.separator));
		BufferedImage bi = ImageIO.read(new File(oldFile));
		int w = bi.getWidth();
		int h = bi.getHeight();
		int maxLength = 350;
		if(w >= h && w > maxLength){
			outputDir = Tool.zipImage(oldFile, outputDir + File.separator, maxLength, maxLength * h / w, 0.5f, "_small");
		}else if(h > w && h > maxLength){
			outputDir = Tool.zipImage(oldFile, outputDir + File.separator, maxLength * w / h, maxLength, 0.5f, "_small");
		}else{
			outputDir = oldFile;
		}
		//获取图像信息
		response.setContentType("text/html");
		System.out.println(outputDir);
		//System.out.println("length：" + geAllPixels(request, outputDir).length());
		response.getWriter().write(geAllPixels(request, outputDir));
	}
	
	private String geAllPixels(HttpServletRequest request, String path){
		Face f = getFace(request, path);
		Face nf = new Face(f.getRgb(), null, f.getWidth(), f.getHeight());
		return JSON.toJSONString(nf);
	}
	
	private static Face getFace(HttpServletRequest request, String path){
		ReadFaces rf = null;
		Face face = null;
		try{
			rf = new DefaultFacesReader(path);
			face = rf.getFace();
		}catch(Exception e){
			e.printStackTrace();
		}catch(Throwable e){
			e.printStackTrace();
		}
		return face;
	}
	
	
	

}